package com.zy.openchat;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.dueeeke.videoplayer.player.VideoViewConfig;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.fanjun.keeplive.KeepLive;
import com.fanjun.keeplive.config.ForegroundNotification;
import com.fanjun.keeplive.config.ForegroundNotificationClickListener;
import com.fanjun.keeplive.config.KeepLiveService;
import com.ja.openchat.R;
import com.ja.openchat.api.ApiUtils;
import com.ja.openchat.http.HttpUtil;
import com.ja.openchat.http.HttpVueClient;
import com.ja.openchat.ui.SplashActivity;
import com.ja.openchat.ui.chat.DebugTbsLogClient;
import com.ja.openchat.ui.chat.group.GroupSendManager;
import com.lqr.emoji.LQREmotionKit;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.xinstall.XInstall;
import com.ycbjie.webviewlib.utils.X5WebUtils;
import com.zy.openchat.core.manager.AuthUserManager;
import com.zy.openchat.core.manager.ChatExCacheManager;
import com.zy.openchat.core.manager.RedPacketManager;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Cockroach;
import com.zy.openchat.util.ForegroundCallbacks;
import com.zy.openchat.util.LocalNotificationHelper;
import com.zy.openchat.util.SimpleActivityLifecycle;
import com.zy.openchat.util.SpeechRecognizerUtil;
import com.zy.openchat.util.videocache.HttpProxyCacheServer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import cn.jpush.android.api.JPushInterface;
import me.goldze.mvvmhabit.base.BaseApplication;
import me.goldze.mvvmhabit.crash.CaocConfig;
import me.goldze.mvvmhabit.utils.FontUtils;
import me.goldze.mvvmhabit.utils.MultiLanguageUtil;

public class App extends MultiDexApplication {
    private static App mInstance;
    public SimpleActivityLifecycle appLifecycle = new SimpleActivityLifecycle();

    @Override
    public void onCreate() {
        super.onCreate();
        //init code...
        mInstance = this;
        Log.d("startsplash","App  restart");
        if (Looper.myLooper() == Looper.getMainLooper()) {

            HttpUtil.init(mInstance, ApiUtils.URL);


            initUtils((Application) getApplicationContext());

            Cockroach.install(new Cockroach.ExceptionHandler() {
                @Override
                public void handlerException(Thread thread, Throwable throwable) {
                    Log.e("handlerException",throwable.getMessage());
                }
            });

            initMVMHabit();

            //初始化提示音
            LocalNotificationHelper.initRingtone(this);

            //前台判断
            registerActivityLifecycleCallbacks(appLifecycle);

            //bugly
            CrashReport.initCrashReport(getApplicationContext(), "72c0061bde", false);

            initQBS();
            SpeechRecognizerUtil.getInstance().init();
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }

//            OkGo.getInstance().init(this);

            initJpush();

            VideoViewManager.setConfig(VideoViewConfig.newBuilder()
                    .setPlayOnMobileNetwork(true)
                    .setEnableOrientation(false)
                    .build());

            ForegroundCallbacks.init(this).addListener(new ForegroundCallbacks.Listener() {
                @Override
                public void onBecameForeground() {
                    TelegramManager.getTelegramManager().setUserState(true);
                }

                @Override
                public void onBecameBackground() {
                    TelegramManager.getTelegramManager().setUserState(false);
                }
            });

            MultiLanguageUtil.init(this);
        }

        if (isMainProcess()) {
            //preInit 必须在Application的onCreate()方法里调用。
//            ShareInstall.getInstance().preInit(getApplicationContext());
            XInstall.init(this);
        }
    }

    private HttpProxyCacheServer proxy;

    public static HttpProxyCacheServer getProxy() {
        App app = App.getInstanse();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer.Builder(this)
                .cacheDirectory(new File(Constants.userVideoPath()))
                .build();
    }

    private void initJpush(){
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

    private void initQBS(){
        X5WebUtils.init(getApplicationContext());
        // 在调用TBS初始化、创建WebView之前进行如下配置
        HashMap map = new HashMap();
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
        QbSdk.initTbsSettings(map);
        QbSdk.setTbsLogClient(new DebugTbsLogClient(getApplicationContext()));
    }

    //启动保活服务
    public void startKeepLiveService() {
        if (KeepLive.keepLiveService == null) {
            //定义前台服务的默认样式。即标题、描述和图标
            ForegroundNotification foregroundNotification = new ForegroundNotification(getResources().getString(R.string.app_name), "后台运行，保证及时收到新消息", R.mipmap.ic_launcher,
                    //定义前台服务的通知点击事件
                    new ForegroundNotificationClickListener() {
                        @Override
                        public void foregroundNotificationClick(Context context, Intent intent) {
                        }
                    });
            //启动保活服务
            KeepLive.startWork(this, KeepLive.RunMode.ENERGY, foregroundNotification,
                    //你需要保活的服务，如socket连接、定时任务等，建议不用匿名内部类的方式在这里写
                    new KeepLiveService() {
                        /**
                         * 运行中
                         * 由于服务可能会多次自动启动，该方法可能重复调用
                         */
                        @Override
                        public void onWorking() {
                        }

                        /**
                         * 服务终止
                         * 由于服务可能会被多次终止，该方法可能重复调用，需同onWorking配套使用，如注册和注销broadcast
                         */
                        @Override
                        public void onStop() {
                        }
                    }
            );
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static App getInstanse() {
        return mInstance;
    }

    //启动必要的服务
    public static void keepAlive(Context context) {
//        if (!isServiceRunning(context, "com.zy.watch.AccessibilityWatchService")) {
//            context.startService(new Intent(context, AccessibilityWatchService.class));
//        }
    }

    //服务是否启动
    public static boolean isServiceRunning(Context context, String str) {
        try {
            List<ActivityManager.RunningServiceInfo> runningServices = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getRunningServices(Integer.MAX_VALUE);
            if (runningServices.size() == 0) {
                return false;
            }
            for (int i = 0; i < runningServices.size(); i++) {
                if (runningServices.get(i).service.getClassName().equals(str)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //是否debug模式
    public static boolean isAppDebugMode(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception x) {
            return false;
        }
    }

    /**
     * 初始化Utils工具
     *
     * @param appcontext
     */
    private static void initUtils(Application appcontext) {
        Utils.init(appcontext);
        LogUtils.getConfig().setGlobalTag(appcontext.getString(R.string.app_name)).setLogSwitch(true);
        LQREmotionKit.init(appcontext, (context, path, imageView) -> Glide.with(context).load(path).apply(new RequestOptions().centerCrop().diskCacheStrategy(DiskCacheStrategy.RESOURCE).dontAnimate()).into(imageView));
    }

    /**
     * MVVMHabit初始化
     */
    private void initMVMHabit() {
        //MVVMHabit初始化
        BaseApplication.setApplication(this);
        //配置全局异常崩溃操作
        CaocConfig.Builder.create()
                .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //背景模式,开启沉浸式
                .enabled(true) //是否启动全局异常捕获
                .showErrorDetails(true) //是否显示错误详细信息
                .showRestartButton(true) //是否显示重启按钮
                .trackActivities(true) //是否跟踪Activity
                .minTimeBetweenCrashesMs(2000) //崩溃的间隔时间(毫秒)
                .errorDrawable(R.mipmap.ic_launcher) //错误图标
//                .restartActivity(LoginActivity.class) //重新启动后的activity
                //.errorActivity(YourCustomErrorActivity.class) //崩溃后的错误activity
                //.eventListener(new YourCustomEventListener()) //崩溃后的错误监听
                .apply();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_Logout: {
                System.out.println("开始退出登录");
                toLoginView();
            }
            break;
        }
    }

    public void toLoginView() {
        Log.d("startsplash","fromapp");
        TelegramManager.getTelegramManager().destroy();
        //清理数据
        TelegramManager.getTelegramManager().cleanCurrentData();
        UserInfo.getUserInfo().reset();
        RedPacketManager.getRedPacketManager().clean();
        //CallManager.getCallManager().reset();
        ChatExCacheManager.reset();
        GroupSendManager.getInstance().clean();
        AuthUserManager.getAuthUserManager().logout();
        //进入鉴权页面
        //SplashActivity.start(this);

        Activity activity = ActivityUtils.getTopActivity();
        if(activity!=null){
            SplashActivity.start(activity);
        }else{
            Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        ContextWrapper wrapper = MultiLanguageUtil.getInstance().wrap(this);
        super.onConfigurationChanged(wrapper.getApplicationContext().getResources().getConfiguration());
    }
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
            Configuration config = res.getConfiguration();
            config.fontScale = FontUtils.getFontScale(MultiLanguageUtil.getInstance().getFontSizeScale());//1 设置正常字体大小的倍数
            res.updateConfiguration(config, res.getDisplayMetrics());
        }
        try {
            if(MultiLanguageUtil.getInstance()!=null){
                Locale locale = res.getConfiguration().getLocales().get(0);
                if(!locale.getDisplayLanguage().equals(MultiLanguageUtil.getInstance().getLanguageLocale().getDisplayLanguage())){
                    MultiLanguageUtil.getInstance().updateLocal(this,res);
                }
            }
        }catch (Exception e){

        }
        return res;
    }

    /**
     * 判断当前进程是否是应用的主进程
     *
     * @return
     */
    public boolean isMainProcess() {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return getApplicationInfo().packageName.equals(appProcess.processName);
            }
        }
        return false;
    }
}